// packageA/pages/home/home.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    appurl: app.apiurl,
    apiimg: app.apiimg,
    id: 0,
    con: '',
    con1: '',
    con2: '可填写寻找比赛队友、王者开黑队友、交友需求；或者个人兴趣爱好、个人特点等内容；展示在首页列表中，最多20个汉字。',
    list: [],
    temppath: [],
    sxlist1: ['收花开黑', '收花带飞', '收花陪聊', '免费开黑', '王者处CP','免费交友','寻找战队','战队招人','其他'],
    order_type: 0,
    yonghu:''
  },
  z_miaoshu(e) {
    this.setData({
      con: e.detail.value
    })
  },
  z_miaoshu1(e) {
    this.setData({
      con1: e.detail.value
    })
  },
  z_upload111() {
    let that = this
    // let num = Number(that.data.peizhi.config_param39) - Number(that.data.list.length)
    let num = 3 - Number(that.data.list.length)
    if (num != 0) {
      wx.chooseMedia({
        count: num,
        sizeType: ["compressed"],
        mediaType: ['image'],
        sourceType: ['album', 'camera'],
        camera: 'back',
        success(res) {
          console.log('222222', res.tempFiles)
          for (let i = 0; i < res.tempFiles.length; i++) {
            var tempFiles = res.tempFiles[i]['tempFilePath'];
            var fileSize = res.tempFiles[i]['size'];
            var MAX_SIZE = Number(that.data.peizhi.config_param39) * 1024 * 1024;
            if (fileSize > MAX_SIZE) {
              console.log('44444', tempFiles)
              wx.showToast({
                title: '文件超过大小限制',
                icon: 'none',
              });
              // 文件超过限制，处理逻辑，比如重新选择
              return;
            } else {
              console.log('33333', tempFiles)
              wx.uploadFile({
                url: 'https://www.zonghengxin.com/api/common/upload',
                filePath: tempFiles,
                name: 'file',
                formData: {},
                success(res) {
                  console.log('66666', res)
                  let list = that.data.list
                  const data = JSON.parse(res.data)
                  console.log('1111', data.data.fullurl)
                  list.push(data.data.fullurl)
                  that.setData({
                    list: list
                  })
                }
              })
            }
          }
        }
      })
    }
  },
  z_upload() {
    let that = this
    let num = 3 - Number(that.data.list.length)
    if (num != 0) {
      wx.chooseImage({
        // 最多可以选择的图片张数
        count: num,
        sizeType: ["compressed"],
        //   选择图片的来源
        sourceType: ["album", "camera"],
        success: function (res) {
          var shangchuan = true;
          for (let i = 0; i < res.tempFilePaths.length; i++) {
            var tempFiles = res.tempFilePaths[i];
            var fileSize = res.tempFiles[i]['size'];
            var MAX_SIZE = Number(that.data.peizhi.config_param39) * 1024 * 1024;
            if (fileSize > MAX_SIZE) {
              wx.showToast({
                title: '文件超过大小限制',
                icon: 'none',
              });
              shangchuan = false;
              // 文件超过限制，处理逻辑，比如重新选择
              return;
            }
          }
          that.setData({
            temppath: res.tempFilePaths
          })
          if (shangchuan) {
            setTimeout(function () {
              that.z_shangchuan()
            }, 1000)
          }
        },
      })
    }
  },
  z_shangchuan() {
    let _this = this
    const filePaths = _this.data.temppath;
    filePaths.forEach((filePath, index) => {
      wx.uploadFile({
        url: 'https://www.zonghengxin.com/api/common/upload',
        filePath: filePath,
        name: 'file',
        formData: {},
        // 超时时间，单位为毫秒
        timeout: 600000000,
        header: {
          "content-type": "multipart/form-data"
        },
        success: (res) => {
          let list = _this.data.list
          const data = JSON.parse(res.data)
          list.push(data.data.fullurl)
          _this.setData({
            list: list
          })
        },
        fail: (err) => {
          console.error(`第 ${index + 1} 个文件上传失败`, err);
        },
        complete: () => {
          // 可选：所有文件上传完成后的操作（需自行判断是否全部完成）
        }
      });
    });
  },
  z_del(e) {
    let _this = this
    let arr = _this.data.list
    arr.splice(e.currentTarget.dataset.index, 1)
    _this.setData({
      list: arr
    })
  },
  z_back() {
    wx.navigateBack({
      delta: 1
    })
  },
  z_fabu() {
    let _this = this
    let order_type = _this.data.order_type;
    if(order_type == '7'){
      order_type = '8'
    } else if(order_type == '8'){
      order_type = '9'
    } else if(order_type == '9'){
      order_type = '7'
    }
    let params = {
      "token": wx.getStorageSync("user_token"),
      "con": _this.data.con,
      "images": _this.data.list,
      "syly_str": _this.data.con1,
      "id": _this.data.id,
      "lylx":order_type
    }
    if(_this.data.order_type == '0'){
      wx.showToast({
        title: '请选择留言类型',
        icon: 'none',
        duration: 2000
      })
    } else {
      wx.request({
        url: app.apiurl + 'api/member/homePageAdd',
        method: 'POST',
        data: params,
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 修改请求
        },
        success(res) {
          if (res.data.code == '1001') {
            _this.z_back()
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 2000
            })
          }
  
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.id != 0) {
      this.setData({
        id: options.id
      })
      let _this = this;
      setTimeout(function () {
        _this.z_show()
      }, 500)
    } else {
      let that = this;
      setTimeout(function () {
        that.z_yonghu()
      }, 500)
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.z_peizhi()
    // this.z_show()
  },
  z_peizhi() {
    let _this = this
    let params = {
      "token": wx.getStorageSync("user_token"),
    }
    wx.request({
      url: app.apiurl + 'api/config/configBase',
      method: 'GET',
      data: params,
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 修改请求
      },
      success(res) {
        _this.setData({
          peizhi: res.data.data
        })
      }
    })
  },
  z_show() {
    let _this = this
    let id = _this.data.id
    if (id != 0) {
      let params = {
        "token": wx.getStorageSync("user_token"),
      }
      wx.request({
        url: app.apiurl + 'api/member/homePageDetail?id=' + id,
        method: 'GET',
        data: params,
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 修改请求
        },
        success(res) {
          _this.setData({
            con: res.data.data.con,
            list: res.data.data.images,
            con1: res.data.data.syly_str,
            con2: res.data.data.syly_str
          })
        }
      })
    }
  },
  z_yonghu() {
    let _this = this
    let params = {
      "token": wx.getStorageSync("user_token"),
    }
    wx.request({
      url: app.apiurl + 'api/member/myInfo',
      method: 'POST',
      data: params,
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 修改请求
      },
      success(res) {
        _this.setData({
          yonghu: res.data.data
        })
        if (res.data.code == '1001') {
          if (res.data.data.syly_str != '') {
            _this.setData({
              con2: res.data.data.syly_str
            })
          }
        }
      }
    })
  },
  z_shaixuan1(e) {
    this.setData({
      order_type: e.currentTarget.dataset.index+1
    })
  },
  
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})